﻿class ApiClient {
    constructor(baseUrl = '/api') {
        this.baseUrl = baseUrl;
    }

    async post(endpoint, data) {
        const url = `${this.baseUrl}/${endpoint}`;
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${this.getToken()}`
            },
            body: JSON.stringify(data)
        });

        if (!response.ok) {
            const errorData = await this.tryParseError(response);
            throw new Error(errorData.message || 'Request failed');
        }

        return await response.json();
    }

    getToken() {
        // 从localStorage或cookie获取token
        return localStorage.getItem('authToken');
    }

    async tryParseError(response) {
        try {
            return await response.json();
        } catch {
            return { message: `HTTP error ${response.status}` };
        }
    }
}



function SetCookie(name, value, daysToExpire) {
    let expires = "";

    if (daysToExpire) {
        const date = new Date();
        date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }

    document.cookie = `${name}=${value || ""}${expires}; path=/`;
}

